package com.geek.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.geek.entity.Course;
import com.geek.service.CourseService;
import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.geek.common.KsdStaticParameter;
import com.geek.utils.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
@RestController
@Log4j2
public class WeixinNavtiveController {
    @Value("${spring.profiles.active}")
    private String profiles;

    @Autowired
    private CourseService courseService;

    /**
     * 付款订单Api,根据传入的订单号 生成付款二维码
     *
     * @param courseid
     * @param response
     */
    @RequestMapping("/weixinpay")
    @ResponseBody
    public byte[] weixinpay(String courseid,HttpServletResponse response) throws JsonProcessingException {

        if (StringUtils.isEmpty(courseid)){
            return null;
        }

        Course course = courseService.getById(courseid);

        if (course == null){
            return null;
        }
        //1:封装请求参数
        Map<String, Object> map = new HashMap();
        map.put("appid", KsdStaticParameter.appId);
        map.put("mchid", KsdStaticParameter.mchId);
        //临时写死配置
        map.put("description", course.getTitle());
        map.put("out_trade_no", new SnowflakeIdWorker(1, 1).nextId() + "");
        map.put("notify_url", KsdStaticParameter.notifyUrl);
        Map<String, Object> amount = new HashMap();
        //订单金额 单位分
        amount.put("total", Integer.parseInt(getMoney(course.getPrice())));
        amount.put("currency", "CNY");
        map.put("amount", amount);

        //附属参数
        Map<String,Object> attachMap = new HashMap<>();
        attachMap.put("courseid", 1);
        attachMap.put("userid", 1);
        map.put("attach", JsonUtil.obj2String(attachMap));

        //2:转换成json字符串，开始微信支付请求
        ObjectMapper objectMapper = new ObjectMapper();
        String body = objectMapper.writeValueAsString(map);
        //3:请求统一微信native下单接口
        Map<String, Object> stringObjectMap = HttpUtils.doPost(KsdStaticParameter.unifiedOrderUrl, body);

        String codeUrl = stringObjectMap.get("code_url").toString();
        //生成付款二维码
        //生成二维码配置
        Map<EncodeHintType, Object> hints = new HashMap<>();
        //设置纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        //编码类型
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        try {
            // 7: 生成微信支付二维码
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            String logopath = null;
            if(profiles.equals("dev")) {
                logopath = ResourceUtils.getFile("classpath:favicon.png").getAbsolutePath();
            }else{
                logopath = ResourceUtils.getFile("/www/web/favicon.png").getAbsolutePath();
            }
            BufferedImage buff = QRCodeUtil.encode(codeUrl, logopath, false);
            ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
            ImageIO.write(buff, "JPEG", imageOut);
            imageOut.close();
            ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
            return FileCopyUtils.copyToByteArray(input);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 元转换成分
     *
     * @param money
     * @return
     */
    private String getMoney(String money) {
        if (money == null || money.equalsIgnoreCase("0")) {
            return "";
        }
        // 金额转化为分为单位
        // 处理包含, ￥ 或者$的金额
        String currency = money.replaceAll("\\$|\\￥|\\,", "");
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = 0l;
        if (index == -1) {
            amLong = Long.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
        } else if (length - index == 2) {
            amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return amLong.toString();
    }
}